import json
from collections import Counter


class Brider:
    @classmethod
    def writeTemp(cls, val):
        with open('./Tmp/MyWorryList.json', 'w') as f:
            json.dump(val, f ,ensure_ascii=False)

    @classmethod
    def readTemp(cls):
        with open('./Tmp/MyWorryList.json', 'r') as f:
            return json.load(f)
    @classmethod
    def writeUser(cls, val, user):
        """
        将错题写到User的错题集里面
        @param val: 所有的错题
        @param user: 存储的用户
        @return:
        """
        path = f"window_source/user/{user}/worry.json"
        try:
            with open(path ,'r') as f:
                worryList = json.load(f)
        except:
            worryList = []

        for i in val:
            worryList.append(i)
        with open(path,'w') as f:
            json.dump(worryList, f, ensure_ascii=False)

    @classmethod
    def readUser(cls, user):
        """
        将错题写到User的错题集里面
        @param val: 所有的错题
        @param user: 存储的用户
        @return:
        """
        path = f"window_source/user/{user}/worry.json"
        try:
            with open(path, 'r') as f:
                worryList = json.load(f)
        except:
            worryList = []

        return worryList

    @classmethod
    def MustCountWorry(cls, user, Top):
        """
        错的最多的几个
        @param Top: 前几个
        @return:
        """
        WorryList = cls.readUser(user)
        ret = dict()
        for i in WorryList:
            ret[json.dumps(i,ensure_ascii=False)] = WorryList.count(i)
        sort = sorted(ret.items(), key=lambda d: d[1],reverse=True)

        ret_list = [json.loads(sort[i][0])+[sort[i][1]] for i in range(Top)]
        return ret_list

    @classmethod
    def Apdate(cls, value, hasCountWorry=None):
        """
        将列表转化成字符
        @param value:
        @param hasCountWorry: 是否有错题次数字段
        @return:
        """

        if hasCountWorry is None:
            hasCountWorry = False
        else:
            hasCountWorry = True

        tmp_str = ""
        for i in value:
            tmp_str += "题干: " + str(i[0]) + "\r\n"
            tmp_str += "A:" + str(i[1]) + "\r\n"
            tmp_str += "B:" + str(i[2]) + "\r\n"
            tmp_str += "C:" + str(i[3]) + "\r\n"
            tmp_str += "D:" + str(i[4]) + "\r\n"
            tmp_str += "答案:" + str(i[5]) + "\r\n"
            tmp_str += "我的答案:" + str(i[6]) + "\r\n\r\n"
            if hasCountWorry:
                tmp_str += "错误次数" + str(i[7]) + "\r\n\r\n"

        return tmp_str
